﻿
namespace DAPNet
{
    public class DerivativeFilter : IOfflineEffect
    {
        private int order;


        public DerivativeFilter(int order)
        {
            this.order = order;
        }

        public int Order
        {
            get 
            { 
                return order; 
            }
            set 
            { 
                order = value; 
            }
        }

        public void Process(SampleCollection samples)
        {
            for (int i = 0; i < order; i++)
            {
                ProcessToDerivative(samples);    
            }
        }
        
        private void ProcessToDerivative(SampleCollection samples)
        {
            SampleCollection clonedSamples = samples.Clone();
            for (int i = 0; i < samples.Count; i++)
            {
                double derivativeValue = GetDerivativeValueAt(clonedSamples, i);
                samples[i].SetTrimmedValue(derivativeValue);
            }
        }

        private double GetDerivativeValueAt(SampleCollection samples, int index)
        {
            double previousValue = Sample.BaseValue;
            if (index > 0)
            {
                previousValue = samples[index - 1].Value;
            }
            double succeedingValue = Sample.BaseValue;
            if (index < samples.Count - 1)
            {
                succeedingValue = samples[index + 1].Value;
            }
            double currentValue = samples[index].Value;
            double derivativeValue = previousValue - (2 * currentValue) + succeedingValue;
            return derivativeValue;
        }
    }
}
